# -*- coding: utf-8 -*-

from odoo.http import request
from odoo_contrib import http as contrib_http
from odoo_contrib.marshal import marshal_with
from odoo_contrib.parser import parse_with

from ..schemas import marshals, parser
from ..utils.exceptions import FrontendException


@contrib_http.route('/exhibition')
class Checkin(contrib_http.Controller):
    @contrib_http.route('/checkin', methods=['POST'])
    @marshal_with(marshals.checkin.CheckinSchema)
    def scan_qrcode(self, **kwargs):
        return request.env['exhibition.checkin'].qrcode_scanned(request.wechat_user)

    @contrib_http.route('/checkin/<int:cid>', methods=['PUT'])
    @parse_with(parser.checkin.CheckinSalesmanSpecifiedParser)
    @marshal_with(marshals.checkin.CheckinSchema)
    def specify_salesman(self, cid, **kwargs):
        params = self.parser.parse()
        checkin = request.env['exhibition.checkin'].browse(cid)
        if not checkin.exists():
            raise FrontendException(
                errcode=200101,
                params={
                    'checkinId': cid,
                }
            )
        salesman = request.env['exhibition.users'].search([
            ('salesman_no', '=', params['salesman_no'])
        ])
        if len(salesman) != 1:
            raise FrontendException(
                errcode=200102,
                params={
                    'salesmanNo': params['salesman_no'],
                }
            )
        checkin.salesman_specified(salesman, request.wechat_user)

        return checkin

